package com.tledu.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGLib {
    public static void main(String[] args) {
        // 创建代理对象
        Enhancer enhancer = new Enhancer();
        // 设置代理的类型
        enhancer.setSuperclass(Cai.class);
        // 设置增强
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("before...");
                Object result = null;
                // 调用真正的方法
                try{
                    result = methodProxy.invokeSuper(o, objects);
                    System.out.println("afterReturning。。。。");
                } catch (Throwable e){
                    System.out.println("afterThrowing");
                    throw e;
                }finally {
                    System.out.println("after");
                }

                return result;
            }
        });

        // 创建代理对象，执行create会调用对应类的构造方法来创建实例
        Cai cai = (Cai) enhancer.create();
        cai.sing("我和我的祖国");
    }
}
